package irri.soils.ssnm;

import java.io.FileOutputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ActivityMain4 extends SSNM implements View.OnClickListener, OnItemClickListener{
	
	private View button1;
	private Bundle b;
	private Intent intent;
	private ArrayList<Integer> refList;
	private ArrayList<String> detail;
	private ArrayList<String> addresses;
	
	private ListView listView1;
	private Button button3;
	private Button button2;
	private ArrayAdapter<Object> adapter;
	private Button button4;
	private RelativeLayout relativeLayout1;
	private RadioButton radio1;
	private RadioButton radio2;
	private RadioButton radio3;
	private RadioButton radio4;
	private RadioButton radio5;
	private LinearLayout linearLayout3;
	private LinearLayout linearLayout4;
	private TextView question;
	private TextView note;
	private int option = 0;
	private Button button5;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main4);
        setCustomTitle();
        b = this.getIntent().getExtras();
        button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(this);
        button1.setEnabled(false);
        button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(this);
        button3 = (Button) findViewById(R.id.button3);
        button3.setOnClickListener(this);
        button3.setEnabled(false);
        button4 = (Button) findViewById(R.id.button4);
        button4.setOnClickListener(this);
        button4.setEnabled(false);
        button5 = (Button) findViewById(R.id.button5);
        button5.setOnClickListener(this);
        radio1 = (RadioButton) findViewById(R.id.radio1);
        radio2 = (RadioButton) findViewById(R.id.radio2);
        radio3 = (RadioButton) findViewById(R.id.radio3);
        radio4 = (RadioButton) findViewById(R.id.radio4);
        radio5 = (RadioButton) findViewById(R.id.radio5);
        radio1.setOnClickListener(this);
        radio2.setOnClickListener(this);
        radio3.setOnClickListener(this);
        radio4.setOnClickListener(this);
        radio5.setOnClickListener(this);
        question = (TextView) findViewById(R.id.question);
        note = (TextView) findViewById(R.id.note);
        question.setText(get("image"));
        
        listView1 = (ListView) findViewById(R.id.listView1);
        listView1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        listView1.setOnItemClickListener(this);
        
        displayView();
        selectAll();
        selectAll();
        if(!checkInternetConnection()){
      	   intent = new Intent(ActivityMain4.this, ActivityB.class);
      	   intent.putExtras(b);
      	   startActivity(intent);
           finish();
        }
        if(responses!=null&&!responses.isEmpty()){
        	relativeLayout1 = (RelativeLayout) findViewById(R.id.relativeLayout1);
        	relativeLayout1.setVisibility(View.GONE);
        	radio1.setOnClickListener(this);
        	radio2.setOnClickListener(this);
        }
    }
    
    public void displayView(){
    	SQLiteDatabase myDB= null;
        try {
            myDB = this.openOrCreateDatabase("SSNM2", MODE_WORLD_WRITEABLE, null);
        Cursor cursor = myDB.rawQuery("select * from phil;", null);
          refList = new ArrayList<Integer>();
          detail = new ArrayList<String>();
          addresses = new ArrayList<String>();
          //System.out.println("Count: "+cursor.getCount());
          if (cursor.moveToFirst()) {
             do {
                refList.add(cursor.getInt(0));
                //System.out.println("==="+cursor.getInt(0));
                String data = cursor.getString(1);
                addresses.add(data);
                detail.add(
                		URLDecoder.decode(data.split("filename=")[1]));
             } while (cursor.moveToNext());
          }
          if (cursor != null && !cursor.isClosed()) {
             cursor.close();
          }
        } catch(Exception e) {
        } finally {
           if(myDB!=null) myDB.close();
        }
        if(adapter!=null) adapter.clear();
        adapter = new ArrayAdapter<Object>(this, R.layout.list_black_text, 
	    		detail.toArray());
        listView1.setAdapter(adapter);
    }
    
    private void selectAll(){
    	boolean b = button2.getText().equals("Select all");
    	int count = listView1.getCount();
    	for(int i=0; i<count; i++)
            listView1.setItemChecked(i, !b);
        for(int i=0; i<count; i++)
        listView1.performItemClick(listView1, i, R.id.list_content1);
    }
    

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.button1:
			try{
			SparseBooleanArray theArray = listView1.getCheckedItemPositions();
			responses = new HashMap<String, String>();
			for(int i = 0; i < theArray.size(); i++){ 
				if(theArray.get(i)){
					if(checkInternetConnection()){
						String response = processHttp(addresses.get(i));
						String num = addresses.get(i).split("&num=|&")[1];
						messageProcess(response, num);
						responses.put(detail.get(i), response);
						//responses.add(object)
						deleteStored(refList.get(i));
						
					}
				}
			}
			intent = new Intent(ActivityMain4.this, ActivityMain4.class);
      	    intent.putExtras(b);
      	    startActivity(intent);
            finish();
			}catch(Exception ex){
				
			}
			break;
		case R.id.button2:
			selectAll();
			break;
		case R.id.button4:
			try{
			SparseBooleanArray theArray = listView1.getCheckedItemPositions();
			for(int i = 0; i < theArray.size(); i++)
				if(theArray.get(i))
					deleteStored(refList.get(i));
			intent = new Intent(ActivityMain4.this, ActivityMain4.class);
      	    intent.putExtras(b);
      	    startActivity(intent);
            finish();
			}catch(Exception ex){
				
			}
			break;
		case R.id.radio1: option = 1; break;
		case R.id.radio2: option = 2; break;
		case R.id.radio3: option = 3; break;
		case R.id.radio4: option = 4; break;
		case R.id.radio5: option = 5; break;
		case R.id.button5:

			if(option==1||option==2){
				if(option==1){
					Iterator<String> it = responses.keySet().iterator();
					while(it.hasNext()){
						String key = it.next();
						String val = (String) responses.get(key);
						try{
							String FILENAME = key;
							String string = val;

							FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
							fos.write(string.getBytes());
							fos.close();
						}catch(Exception ex){
							System.out.println(ex.toString());
						}
					}
					note.setText(get("image2")+"\n\n"+get("suggest"));
				}
				else note.setText(get("image3")+"\n\n"+get("suggest"));
				responses = null;
				linearLayout4 = (LinearLayout) findViewById(R.id.linearLayout4);
				linearLayout4.setVisibility(View.VISIBLE);
				linearLayout3 = (LinearLayout) findViewById(R.id.linearLayout3);
				linearLayout3.setVisibility(View.GONE);
			}
			switch(option){
				case 3:
				case 4:
					String name = b.getString("name");
					int lang = b.getInt("lang");
					b.clear();
					if(option==3) b.putString("name", name);
					b.putInt("lang", lang);
					intent.putExtras(b);
					startActivity(intent);
					break;
				case 5:
					finish(); 
					break;
			}
		}
	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent(ActivityMain4.this, SSNM.prevActivity==null ? 
				ActivityMain3.class : SSNM.prevActivity.getClass());
		intent.putExtras(b);
		startActivity(intent);
		finish();
	}

	/* (non-Javadoc)
	 * @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long)
	 */
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		SparseBooleanArray theArray = listView1.getCheckedItemPositions();
		int counter = 0; for(int i = 0; i < theArray.size(); i++){ 
			if(theArray.get(i)){ 
				counter++; }}
		button1.setEnabled(counter!=0);
		button4.setEnabled(counter!=0);
		button2.setText(counter==listView1.getCount() ? "Unselect all" : "Select all");
		button3.setEnabled(counter==1);
	}
}